package top.lshaci.learning.netty.tcp;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.CharsetUtil;

/**
 * TcpServer
 *
 * @author lshaci
 * @since 1.0.0
 */
public class TcpServer {

    public static void main(String[] args) {
        EventLoopGroup boss = new NioEventLoopGroup(1);
        EventLoopGroup worker = new NioEventLoopGroup();

        try {
            ServerBootstrap server = new ServerBootstrap();
            server.group(boss, worker)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            final ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new MessageDecoder());
                            pipeline.addLast(new MessageEncoder());
                            pipeline.addLast(new SimpleChannelInboundHandler<MessageProtocol>() {
                                @Override
                                protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {
                                    byte[] content = msg.getContent();
                                    String s = new String(content, CharsetUtil.UTF_8);
                                    System.err.println("接收到消息：" + s);

                                    String resp = s.substring(0, 1) + " => 小伙子少吃点";
                                    final byte[] bytes = resp.getBytes(CharsetUtil.UTF_8);
                                    final MessageProtocol messageProtocol = new MessageProtocol(bytes.length, bytes);
                                    ctx.writeAndFlush(messageProtocol);
                                }

                                @Override
                                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                                    cause.printStackTrace();
                                    ctx.close();
                                }
                            });
                        }
                    });
            final ChannelFuture future = server.bind(7000).sync();
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            worker.shutdownGracefully();
            boss.shutdownGracefully();
        }
    }
}
